<template>
  <view class="container" v-if="fee && fee.orderFeeList">
    <ve-card :title="item.feeName" type="none" v-for="(item, index) in fee.orderFeeList" :key="item">
      <template #status>
        <view class="status-2">{{ item.feeTypeName }}</view>
        <view class="status-1">{{ item.costTypeName }}</view>
      </template>
      <ve-cell-price :label="costType == 10 ? '应收金额' : '应付金额'" :value="Math.abs(item.totalAmount)"></ve-cell-price>
      <ve-cell-price :label="costType == 10 ? '待收金额' : '待付金额'" :value="Math.abs(item.totalAmount)"></ve-cell-price>
      <ve-cell label="订单号">{{ item.shortOrder.orderCode }}</ve-cell>
      <ve-cell label="承租人">{{ item.shortOrder.memberName }}</ve-cell>
      <ve-cell label="车牌号">{{ item.shortOrder.carLicenseNo }}</ve-cell>
      <ve-cell label="租赁周期">{{ item.shortOrder.startTime }} - {{ item.shortOrder.endTime }}</ve-cell>
      <ve-cell label="">
        <text class="c3 fs30 fw400">租期：{{ item.shortOrder.rentDays }}</text>
      </ve-cell>
      <view class="fee-item">
        <view class="fee-table">
          <!-- 表头 -->
          <view class="tlt">
            <view>费用名称</view>
            <view>费用金额</view>
            <view>费用备注</view>
          </view>
          <view style="border: 2rpx solid #f7f8fa; padding-bottom: 22rpx">
            <!-- 1级 -->
            <view class="fee-first">
              <view @click="open1(index)">
                <text style="margin-right: 12rpx">{{ item.feeName }}</text>
                <ve-icon v-if="item.feeDetailList.length && item.open" name="arrow_top" size="28" />
                <ve-icon v-if="item.feeDetailList.length && !item.open" name="arrow_bottom" size="28" />
              </view>
              <view>{{ numFormatThousands(item.activeTotalAmount, 1) }}</view>
              <view class="more-remark" @click="showRemark(item.remark)">{{ item.remark }}</view>
            </view>
            <!-- 2级， 3级 -->
            <block v-if="item.feeDetailList && item.feeDetailList.length > 0 && !item.open">
              <view class="fee-other">
                <!-- 2级 -->
                <block v-for="(el, elindex) in item.feeDetailList" :key="elindex">
                  <view class="twice">
                    <view @click="open2(index, elindex)">
                      <text style="margin-right: 12rpx">{{ el.type == 0 ? el.feeCategoryName : el.itemName }}</text>
                      <ve-icon v-if="el.childrenList.length && el.open" name="arrow_top" size="28" />
                      <ve-icon v-if="el.childrenList.length && !el.open" name="arrow_bottom" size="28" />
                    </view>
                    <view>{{ numFormatThousands(el.activeAmount, 1) }}</view>
                    <view class="more-remark" @click="showRemark(el.remark)">{{ el.remark }}</view>
                  </view>
                  <!-- 3级 -->
                  <block v-if="el && el.childrenList && el.childrenList.length > 0 && !el.open">
                    <view class="third" v-for="(pl, plindex) in el.childrenList" :key="plindex">
                      <view>{{ pl.itemName }}</view>
                      <view>{{ numFormatThousands(pl.activeAmount, 1) }}</view>
                      <view class="more-remark" @click="showRemark(pl.remark)">{{ pl.remark }}</view>
                    </view>
                  </block>
                </block>
              </view>
            </block>
          </view>
        </view>
      </view>
    </ve-card>
    <!-- 表单 -->
    <ve-form ref="veFormRef" :model="form" :rules="rules">
      <ve-card style="overflow: hidden" type="none" fold v-model:initFold="foldStatus.fold1">
        <ve-form-item :label="costName + '金额'" unit="元" required>
          <ve-input-number v-model="form.actualAmount" :precision="2" disabled />
        </ve-form-item>
        <ve-form-item
          :label="costName + '方式'"
          required
          prop="paymentWay"
          labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
        >
          <ve-picker-inline
            v-model="form.paymentWay"
            placeholder="请选择"
            :range="paywayEnum"
            unit="arrowRight"
            @change="typeChange"
          ></ve-picker-inline>
        </ve-form-item>
        <ve-form-item v-if="form.paymentWay == -1" label="结算主体" required prop="account">
          <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight" />
        </ve-form-item>
        <ve-form-item v-else :label="costName + '账号'" labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。">
          <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight"></ve-picker-inline>
        </ve-form-item>
        <ve-form-item v-if="form.paymentWay && form.paymentWay != -1" :label="costName + '时间'" required prop="paymentTime">
          <ve-date-picker v-model="form.paymentTime" title="时间"></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="客户名称" required prop="customerName">
          <ve-input v-model="form.customerName" placeholder="请输入" :maxlength="20" />
        </ve-form-item>
        <ve-form-item :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
          <ve-input v-model="form.customerAccount" placeholder="请输入" :maxlength="20" />
        </ve-form-item>
        <ve-form-item label="结算备注" :borderBottom="false" labelPosition="top">
          <ve-input type="textarea" v-model="form.settlementRemark" placeholder="请输入备注" :maxlength="200" />
        </ve-form-item>
      </ve-card>
    </ve-form>

    <view style="height: 280rpx">
      <ve-bottom-box>
        <view class="bottom-btns">
          <view class="amount">
            {{ costName }}金额：
            <text class="amount-num">
              {{ receiveAmount }}
            </text>
            <text class="amount-pic">元</text>
          </view>
          <view class="line"></view>
          <ve-button type="primary" @click="formSubmit" style="width: 100%" :loading="okLoading">确认</ve-button>
        </view>
      </ve-bottom-box>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { toConfirm, getAccountByPageData, getAccountByWayAndType, confirmFee } from '@/api/dict/detail'
  import useToast from '@/hooks/useToast'
  import useFormFold from '@/hooks/useFormFold'
  import { numFormatThousands } from '@/vehicle-ui/utils/tools.js'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'
  import { userStore } from '@/stores'

  const userInfoStore = userStore()
  const okLoading = ref(false)

  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['paymentTime', 'paymentWay', 'customerName', 'account'],
    },
  ])
  const veFormRef = ref()
  const costType = ref()
  const pagefrom = ref() //判断页面回退 expense详情页  mergeConfirm合并页
  const receiveAmount = ref(0)
  const paywayEnum = ref() //收付款方式
  const accountList = ref() //收付款账号
  const costName = ref() //收款or付款
  const idList = ref([])
  const fee = ref<any>()
  const form = ref<any>({})
  const disabledCostType = ref(false)
  const orderFeeList = ref<any>([])

  const rules = ref<any>({
    paymentTime: {
      required: true,
      message: '请选择',
    },
    paymentWay: {
      required: true,
      message: '请选择',
    },
    actualAmount: {
      required: true,
      message: '请输入',
    },
    customerName: {
      required: true,
      message: '请输入',
    },
  })

  const getDetail = async () => {
    const res: any = await toConfirm({ idList: idList.value })
    console.log('short getDetail: ', res.result)

    receiveAmount.value = Math.abs(res.result.receiveAmount) //合计（取绝对值）
    form.value.actualAmount = Math.abs(res.result.receiveAmount) //固定金额，不可修改
    var datafee = res.result
    orderFeeList.value = datafee.orderFeeList
    // 嵌入展开收起open
    if (datafee.orderFeeList && datafee.orderFeeList.length > 0) {
      datafee.orderFeeList.forEach((item: any) => {
        item.tableOpen = false //控制单个费用 整个表的显示隐藏
        item.open = false //控制1级
        if (item.feeDetailList && item.feeDetailList.length > 0) {
          item.feeDetailList.forEach((el: any) => {
            el.open = false //控制2级
            if (el.childrenList && el.childrenList.length > 0) {
              el.childrenList.forEach((pl: any) => {
                pl.open = false
              })
            }
          })
        }
      })
    }
    fee.value = datafee
    form.value.paymentTime = fee.value.orderFeeList[fee.value.orderFeeList.length - 1]?.createTime //默认时间
    form.value.customerName = fee.value.orderFeeList[fee.value.orderFeeList.length - 1]?.shortOrder.memberName //默认客户
    costType.value = res.result.costType
    if (costType.value == 10) {
      costName.value = '收款'
    } else {
      costName.value = '付款'
    }
    // 押金抵扣为固定收付款方式
    if (res.result.payType != null) {
      disabledCostType.value = true
      form.value.paymentWay = res.result.payType.toString()
    }
    form.value.orderId = fee.value.orderFeeList[0]?.orderId
    getType()
  }
  // 1级
  const open1 = (index: number) => {
    fee.value.orderFeeList[index].open = !fee.value.orderFeeList[index].open //1级
    fee.value.orderFeeList[index].feeDetailList.forEach((item: any) => {
      item.open = true //2级
    })
  }
  // 2级
  const open2 = (index: number, elindex: any) => {
    fee.value.orderFeeList[index].feeDetailList.forEach((item: any, itemindex: any) => {
      if (itemindex == elindex) {
        item.open = !item.open
      }
    })
  }
  // 收付款类型（方式）
  const getType = () => {
    const is_offline = orderFeeList.value.every((item: any) => item.feeType == 1)
    console.log('is_offline', is_offline)

    const is_collection = orderFeeList.value.every((item: any) => item.costType == 10)
    console.log('is_collection', is_collection)

    // 是否包含租车押金和违章押金
    const is_contain_rent_violation = orderFeeList.value.some((item: any) => item.feeNameId == 12 || item.feeNameId == 13)
    console.log('is_contain_rent_violation', is_contain_rent_violation)

    let is_show_jialian = false
    if (orderFeeList.value.length == 1 && is_collection && form.value.actualAmount > 0) {
      is_show_jialian = true
    } else if (orderFeeList.value.length > 1) {
      if (is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      } else if (!is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      }
    }
    console.log('is_show_jialian', is_show_jialian)

    const enterpriseDetail = ref<any>({})
    userInfoStore.setEpDetail(false).then((res) => {
      console.log('setEpDetail', res)
      enterpriseDetail.value = res

      console.log('嘉联聚合支付判断', enterpriseDetail.value.jialianEnabled, form.value.actualAmount)

      getAccountByPageData({ type: costType.value == 10 ? 0 : 1 }).then((res: any) => {
        let newarr: any[] = []
        const data = res.result

        data.forEach((i: any, index: number) => {
          if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '5' && disabledCostType.value) {
            newarr.push(i)
          } else if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '4' && i.way != '5' && !disabledCostType.value) {
            newarr.push(i)
          }

          /**
           * 不显示嘉联聚合支付
           * enterpriseDetail.value.jialianEnabled: 0 未开通嘉联聚合支付
           * actualAmount: 收款金额小于等于0
           * is_offline: 不是线下费用时
           * is_show_jialian: 是否显示嘉联聚合支付，默认不显示
           * is_contain_rent_violation: 是否包含租车押金和违章押金
           */
          if (enterpriseDetail.value.jialianEnabled == 0 || !is_show_jialian || !is_offline || is_contain_rent_violation) {
            newarr = newarr.filter((el) => el.way != '-1')
          }

          if (data.length == index + 1) {
            var children = newarr.map((childItem) => {
              return {
                value: childItem.way,
                label: childItem.wayStr,
                type: childItem.type,
              }
            })
            paywayEnum.value = children
          }
        })
        if (form.value.paymentWay) {
          typeChange(form.value.paymentWay)
        }
      })
    })
  }
  // 账号
  const typeChange = (e: string | number) => {
    if (e == -1) {
      rules.value.account = {
        required: true,
        message: '请选择',
      }
    } else {
      delete rules.value.account
    }

    form.value.account = ''

    paywayEnum.value.forEach((el: any) => {
      if (el.value == e) {
        getAccountByWayAndType({ way: Number(el.value), type: costType.value == 10 ? 0 : 1 }).then((res: any) => {
          var children = res.result.map((childItem: any) => {
            return {
              value: childItem.id,
              label: form.value.paymentWay != -1 ? childItem.account + '_' + childItem.bank : childItem.bank,
            }
          })

          if (children.length == 1 && form.value.paymentWay == -1) {
            form.value.account = children[0].value
          }

          accountList.value = children
        })
      }
    })
  }
  // 提交
  const formSubmit = () => {
    okLoading.value = true
    veFormRef.value.validate((valid: any, errors: any) => {
      if (valid) {
        confirmFee({ ...form.value })
          .then((res: any) => {
            okLoading.value = false
            if (res.code == 200) {
              okLoading.value = false
              if (form.value.paymentWay == -1) {
                const from =
                  pagefrom.value == 'mergeConfirm'
                    ? 'order/short-order/detail/mergeConfirmation'
                    : 'order/short-order/detail/confirmExpenses'
                uni.navigateTo({
                  url: `/pages/common/components/qrcode?id=${res.result}&from=${from}`,
                })
              } else {
                useToast({
                  title: '确认成功',
                }).then(() => {
                  setTimeout(() => {
                    if (pagefrom.value == 'orderList') {
                      useLoadDataAndHotUpdateNavigateBack()
                    }
                    if (pagefrom.value == 'expense') {
                      uni.navigateBack({ delta: 1 })
                      uni.$emit('operateSuccess')
                    }
                    if (pagefrom.value == 'mergeConfirm') {
                      uni.navigateBack({ delta: 2 })
                    }
                  }, 500)
                })
              }
            }
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors)
        okLoading.value = false
        console.log('验证失败', errors)
      }
    })
  }
  const showRemark = (text: string) => {
    uni.showModal({
      title: '备注',
      content: text,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      },
    })
  }
  onLoad((options: any) => {
    if (options.idList) {
      idList.value = JSON.parse(options.idList)
      form.value.idList = idList.value
      getDetail()
    }
    if (options.pagefrom) {
      pagefrom.value = options.pagefrom
    }
  })
</script>

<style lang="scss" scoped>
  page {
    background: #f7f8fa;
  }
  .container {
    padding: 24rpx;
  }
  .viewports {
    background: #f7f8fa;
    display: flex;
    flex-direction: column;
    padding: 24rpx;
  }
  .status-1 {
    background: #fff7e8;
    color: #ff7d00;
    border: 2rpx solid #ff7d00;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .status-2 {
    background: #e8f7ff;
    color: #3491fa;
    border: 2rpx solid #3491fa;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .status-4 {
    background: #f5e8ff;
    color: #722ed1;
    border: 2rpx solid #722ed1;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .line {
    width: 100%;
    background: #d8d8d8;
    height: 1rpx;
  }

  .fee-item {
    overflow-x: scroll;
    margin: 24rpx 0;
    .fee-table {
      width: 800rpx;
      .tlt {
        width: 100%;
        height: 88rpx;
        background: #f7f8fa;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #8491a8;
        font-size: 24rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-first {
        width: 100%;
        margin: 32rpx 0 16rpx;
        background: #ffffff;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #191c27;
        font-size: 28rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-other {
        margin-left: 22rpx;
        .twice {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view {
            margin-top: 24rpx;
          }
          view:nth-child(1) {
            width: 296rpx;
            margin-left: 24rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
        .third {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view:nth-child(1) {
            width: 248rpx;
            margin-left: 48rpx;
          }
          view:nth-child(2) {
            width: 120rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
      }
    }
  }
  .bottom-btns {
    width: 100%;
    display: flex;
    flex-direction: column;
    .amount {
      color: #1e1e1e;
      font-size: 32rpx;
      font-weight: 400;
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;
      margin: 12rpx 0 36rpx;
      .amount-num {
        color: #fe615a;
        font-size: 48rpx;
        font-weight: 600;
        line-height: 1;
      }
      .amount-pic {
        color: #fe615a;
        font-size: 24rpx;
        font-weight: 400;
        margin-left: 8rpx;
      }
    }
    .line {
      width: 100%;
      background: #d8d8d8;
      height: 1rpx;
      margin-bottom: 32rpx;
      transform: scaleY(0.5);
    }
  }
  .more-remark {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }
  :deep(.ve_tooltip__popper) {
    width: 420rpx;
    line-height: 38rpx;
    white-space: normal;
  }
</style>
